package com.yue92.datalife.helper;

import com.yue92.datalife.common.CodeEnum;
import com.yue92.datalife.exception.UncheckedException;
import com.yue92.datalife.model.User;
import com.yue92.datalife.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class UserHelper {

    @Autowired
    IUserService userService;

    public String login(String email, String password) {
        Optional<User> userOptional = userService.getByCertificate(email, password);
        if (!userOptional.isPresent()) {
            throw new UncheckedException(CodeEnum.FAILURE, "certificate invalid");
        }
        User user = userOptional.get();
        if (user.getBanned()) {
            throw new UncheckedException(CodeEnum.FAILURE, "user has banned");
        }

        userService.deleteOldToken(user.getId());

        return userService.generateToken(user.getId());
    }

    public void logout(User user) {
        userService.deleteOldToken(user.getId());
    }

}
